﻿using System;
using System.Text;
using System.Web.UI;
using DeGiglio.biz.Twitter.Classes;
using DeGiglio.biz.Twitter.Properties;
using Microsoft.SharePoint;
using webparts = DeGiglio.biz.Twitter.SharePoint.Webparts;

namespace DeGiglio.biz.Twitter.UserControls
{
    public partial class DisplayTweets : UserControl
    {
        #region " Properties "
        /// <summary>
        /// The DisplayTweetsWebpart property is used by the parent web part to pass itself to this control.
        /// This allows us to use all the user-specified web part properties without having to redefine them
        /// in the control.
        /// </summary>
        public webparts.DisplayTweets DisplayTweetsWebpart { get; set; }
        #endregion

        #region " Controls "
        // The following controls appear here rather than using a .designer.cs file
        protected global::System.Web.UI.WebControls.Literal ltJScriptVars;
        protected global::System.Web.UI.WebControls.Literal ltStyleSheet;
        protected global::System.Web.UI.ScriptManagerProxy managerProxy;
        protected global::System.Web.UI.WebControls.Label lblDisplayTweetsNotConfigured;
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.DisplayTweetsWebpart.TwitterScreenName))
            {
                lblDisplayTweetsNotConfigured.Text = Common.GetResourceValue("ExceptionMessage_WebpartNotConfigured", Common.LocaleID);
                lblDisplayTweetsNotConfigured.Visible = true;
            }
            else
            {
                lblDisplayTweetsNotConfigured.Visible = false;
                LoadScripts();
            }
        }

        /// <summary>
        /// The LoadScripts method is used primarily to add the client-side script files to the page's Script Manager object.
        /// Secondarily, the link to the proper css file is also loaded in this method.
        /// </summary>
        private void LoadScripts()
        {
            string stylePath;
            if (!string.IsNullOrEmpty(this.DisplayTweetsWebpart.CustomCss))
            {
                stylePath = ltStyleSheet.ResolveUrl(this.DisplayTweetsWebpart.CustomCss);
            }
            else
            {
                stylePath = ltStyleSheet.ResolveUrl(ProjectSettings.Default.CssPath_DisplayTweets);
            }

            ltStyleSheet.Text = string.Format(ProjectSettings.Default.HtmlTemplate_CssLink, stylePath);

            string webSvcUrl = SPContext.Current.Web.Url + ProjectSettings.Default.WebSvcPath;
            ltJScriptVars.Text = string.Format(ProjectSettings.Default.HtmlTemplate_VariableScript,
                                               webSvcUrl, 
                                               BuildParams(), 
                                               GetTemplateUrl(), 
                                               ProjectSettings.Default.TemplatePath_TwitterError);
            
            if (! this.DisplayTweetsWebpart.JQueryOnMasterPage)
                managerProxy.Scripts.Add(new ScriptReference(ProjectSettings.Default.jQueryPath));
            if (! this.DisplayTweetsWebpart.JTemplateOnMasterPage)
                managerProxy.Scripts.Add(new ScriptReference(ProjectSettings.Default.jTemplatePath));
            if (! this.DisplayTweetsWebpart.JTimerOnMasterPage)
                managerProxy.Scripts.Add(new ScriptReference(ProjectSettings.Default.jTimerPath));

            managerProxy.Scripts.Add(new ScriptReference(ProjectSettings.Default.ScriptPath_DisplayTweets));
        }

        /// <summary>
        /// The BuildParams method is used to build a string containing the parameters which will be passed to the LoadTweets 
        /// web service. We need to assemble this string here since jQuery will be making the web service call.
        /// </summary>
        /// <returns>The list of parameter names and values to be stored on the page as a JavaScript variable</returns>
        private string BuildParams()
        {
            StringBuilder paramBuilder = new StringBuilder();
            paramBuilder.Append("{\"screenName\":\"");
            paramBuilder.Append(this.DisplayTweetsWebpart.TwitterScreenName + "\",");
            paramBuilder.Append("\"listName\":\"");
            paramBuilder.Append(this.DisplayTweetsWebpart.TwitterListName + "\",");
            paramBuilder.Append("\"requestedItems\":\"");
            paramBuilder.Append(this.DisplayTweetsWebpart.NumberOfTweetsToDisplay + "\",");
            paramBuilder.Append("\"cacheWindow\":\"");
            paramBuilder.Append(this.DisplayTweetsWebpart.CacheTimespan + "\",");
            paramBuilder.Append("\"includeRetweets\":\"");
            paramBuilder.Append(this.DisplayTweetsWebpart.IncludeRetweets.ToString().ToLower() + "\",");
            paramBuilder.Append("\"loadAvatarsUsingSsl\":\"");
            paramBuilder.Append(this.DisplayTweetsWebpart.LoadAvatarsUsingSsl.ToString().ToLower() + "\",");
            paramBuilder.Append("\"conKey\":\"");
            paramBuilder.Append(this.DisplayTweetsWebpart.TwitterConsumerKey + "\",");
            paramBuilder.Append("\"conSec\":\"");
            paramBuilder.Append(this.DisplayTweetsWebpart.TwitterConsumerSecret + "\",");
            paramBuilder.Append("\"localeId\":\"");
            paramBuilder.Append(Common.LocaleID.ToString() + "\"}");

            return paramBuilder.ToString();
        }

        /// <summary>
        /// The GetTemplateUrl method is used to determine which file to pass to the jTemplate library for display of the Tweets table.
        /// The determination is based on a combination of web part properties and if a custom template file has been provided
        /// </summary>
        /// <returns>The path to the desired template</returns>
        private string GetTemplateUrl()
        {
            if (!string.IsNullOrEmpty(this.DisplayTweetsWebpart.CustomTemplate))
                return this.DisplayTweetsWebpart.CustomTemplate;

            // no header, no footer, with avatar, with user name
            if (this.DisplayTweetsWebpart.ShowAvatars && this.DisplayTweetsWebpart.ShowScreenNames)
                return ProjectSettings.Default.TemplatePath_TweetTableDefault;

            // no header, no footer, with avatar, no user name
            if (this.DisplayTweetsWebpart.ShowAvatars && (!this.DisplayTweetsWebpart.ShowScreenNames))
                return ProjectSettings.Default.TemplatePath_TweetTableNoUsernames;

            // no header, no footer, no avatar, with user name
            if ((!this.DisplayTweetsWebpart.ShowAvatars) && this.DisplayTweetsWebpart.ShowScreenNames)
                return ProjectSettings.Default.TemplatePath_TweetTableNoAvatar;

            // no header, no footer, no avatar, no user name
            if ((!this.DisplayTweetsWebpart.ShowAvatars) && (!this.DisplayTweetsWebpart.ShowScreenNames))
                return ProjectSettings.Default.TemplatePath_TweetTableNoAvatarNoUsernames;

            // Couldn't determine the desired pattern, so return the default template
            return ProjectSettings.Default.TemplatePath_TweetTableDefault;
        }
    }
}
